package com.nl.controller.web.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.catalina.LifecycleListener;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nl.controller.common.annotation.SystemServiceLog;
import com.nl.controller.common.exception.SmsException;
import com.nl.controller.common.service.CommonService;
import com.nl.controller.web.bean.ChangeData;
import com.nl.controller.web.mapper.ChangeSynchronizationMapper;
import com.nl.controller.web.util.GZipUtil;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class ChangeSynchronizationInterfaceService {
    @Autowired
    private ChangeSynchronizationMapper changeSynchronizationMapper;
    @Autowired
	private CommonService commonService;
	
	//private final String changeSynchronizationUrl="http://10.32.45.139:8080";//老项目变更同步
    //private final String changeSynchronizationUrl="http://10.209.169.125:8080"; //新项目变更同步
    private final String changeSynchronizationUrl="http://10.32.248.23:18993"; //it接口机

	
   // @SystemServiceLog(description = "获取流水号序列", value = false)
    public String getStreamSeq() {
        String streamSeq;
        try {
        	streamSeq = changeSynchronizationMapper.getStreamSeq();
        	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
          	streamSeq = sdf.format(new Date())+streamSeq;
        
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取流水号序列");
            throw new SmsException("获取流水号序列");
        }
        return streamSeq;
    }
	
	@SystemServiceLog(description = "通过项目id获取变更信息", value = false)
	public ChangeData findChangeByMgrId(String mgrId) {
		ChangeData changeData;
		changeData = changeSynchronizationMapper.findChangeByMgrId(mgrId);
		String checkState = changeData.getCheckState();
		if("0".equals(checkState)){checkState = "2";}
		else if("3".equals(checkState)){checkState = "1";}
		else if("2".equals(checkState)){checkState = "0";}
		else if("1".equals(checkState)){checkState = "3";}
		changeData.setCheckState(checkState);
		return changeData;
	}
	//@SystemServiceLog(description = "通过项目id获取变更信息", value = false)
	public List<ChangeData> findChange() {
		List<ChangeData> changeDatas = new ArrayList<ChangeData>();
		changeDatas = changeSynchronizationMapper.findChange();
		for (ChangeData changeData : changeDatas) {
			String checkState = changeData.getCheckState();
			if("0".equals(checkState)){checkState = "2";}//待审核
			else if("3".equals(checkState)){checkState = "1";}//审核不通过
			else if("2".equals(checkState)){checkState = "0";}//审核通过
			else if("1".equals(checkState)){checkState = "3";}//审核中
			changeData.setCheckState(checkState);
		}
		
		return changeDatas;
	}

//	@SystemServiceLog(description = "项目变更同步接口", value = false)
	public Map<String, Object> changeSynchronization(com.alibaba.fastjson.JSONObject json){
		Map<String,Object> map=new HashMap<String, Object>();
        String resultCode="-1";
        String resultDesc="";
        JSONObject req = new JSONObject(json);
        String resp="";
        try {
            //System.out.println(req.toJSONString());
          	 resp=this.httpPostWithJSON(changeSynchronizationUrl, req);
        	 //resp = "{\"resultCode\":\"0\",\"resultDesc\":\"成功\",\"streamSeq\":\"20190704110306100001\"}";
          	//log.info("项目变更同步接口回参(解压前)：{}",resp);
          	 resp = GZipUtil.gunzip(resp);
          	//log.info("项目变更同步接口回参(解压后：{}",resp);
          	 map=this.readSmsChangeResp(resp);
      	     //log.info(" 项目信息：{}", map.toString());
		} catch (Exception e){
			resultDesc="项目变更同步接口异常,error:"+e.getMessage();
			map.put(" resultCode", resultCode);
		  	map.put("resultDesc", resultDesc);
			e.printStackTrace();
		}
  	  	return map;
}

    public static void main(String[] args) {
        System.out.println("---"+GZipUtil.gunzip("H4sIAAAAAAAAAD2PQXKCMABF78I6nYEoaroDRdAShzQi6MYBE1ODKAgotNN9p6veoKdrz9G0i/7l\n" +
                "+zN//nvRcnGZMe1eM/TfQIRMDWgXXjXHenxmXDX6P5jwaqfA99vH1/unolWd1IfzacYqRaMKho8s\n" +
                "M8Po2HKnf5UI41yAbtillKGGbG7buFoLy95ncwKCm5+R+Sq3/VOPO5Op28HQIEAvREvltHRPyBvt\n" +
                "oi6U0nYEMDzhtYtlDU1rTQ04X+E9U9vyaTTApUQl3DwP0Z13s2QfEyDSQPTIJkin3dhfoBWk+qyx\n" +
                "gBtjbKf0WhTBkg+KwDgkV/XkwcI7FjjMJ3GT0G2YTYykJH92F57klJdKTnv9ARtUikoqAQAA"));
    }
	public String httpPostWithJSON(String url, JSONObject jsonParam)
            throws Exception {
        DefaultHttpClient httpclient = null;
        HttpPost httpPost = null;
        HttpResponse response = null;
        org.apache.http.HttpEntity entity = null;
        String result = "";
        try {
            httpclient = new DefaultHttpClient();
            httpPost = new HttpPost(url);
            StringEntity entityParam = new StringEntity(jsonParam.toString(),
                    "utf-8");// 解决中文乱码问题
            entityParam.setContentEncoding("UTF-8");
            entityParam.setContentType("application/json");
            httpPost.setEntity(entityParam);
            // 设置连接超时时间
            HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),
                    20000);
            // 设置读数据超时时间
            HttpConnectionParams.setSoTimeout(httpclient.getParams(), 20000);
            response = httpclient.execute(httpPost);
            entity = response.getEntity();
            if (null != entity) {
                byte[] bytes = EntityUtils.toByteArray(entity);
                result = new String(bytes, "UTF-8");
            } 
            return result;
        } catch (Exception e) {
            throw e;
        } finally {
            if (null != httpclient) {
                httpclient.getConnectionManager().shutdown();
            }
        }
    }
	private Map<String, Object> readSmsChangeResp(String resp){
        String resultCode="-1";
        String resultDesc="失败";
        String streamSeq = "";
        Map<String, Object> retMap=new HashMap<String, Object>();
        if(resp!=null&&!"".equals(resp)){
        	JSONObject jsonObject=JSONObject.parseObject(resp);
//            JSONArray content=JSONArray.parseArray(jsonObject.getString("content"));
//            if(content!=null&&content.size()>0){
//            	resultCode="0";
//            	resultDesc="成功";
//            }
        	resultCode = jsonObject.getString("resultCode");
            resultDesc = jsonObject.getString("resultDesc");
        	streamSeq = jsonObject.getString("streamSeq");
            /*if(streamSeq!=null&&!"".equals(streamSeq)){
            	resultCode="0";
            	resultDesc="成功";
            }*/
//            retMap.put("content", content);
        }
        retMap.put("resultCode", resultCode);
        retMap.put("resultDesc", resultDesc);        
        retMap.put("streamSeq", streamSeq);
        return retMap;
	}
}




